import { Role } from '@/constants/power';
import StaffReducer from '@/dva/application/staff';
import { listArea, listWorkerType } from '@/services/user';
import UserReducer from '@/dva/user';
import { setAuthority } from '@/utils/authority';
import { reloadAuthorized } from '@/utils/Authorized';

const { Namespace, State, Reducers, Effects } = UserReducer;

const UserModel = {
  namespace: Namespace,
  state: State,
  effects: {
    *[Effects.getArea](_, { call, put }) {
      // TODO: 调用接口,获取全部区域
      const response = yield call(listArea);
      yield put({
        type: 'saveArea',
        payload: response,
      });
    },
    *[Effects.listWorkerType](_, { call, put }) {
      // TODO: 调用接口,获取全部区域
      const response = yield call(listWorkerType);
      yield put({
        type: Reducers.saveWorkerType,
        payload: response,
      });
    },
    *[Effects.getCurrentUser](_, { call, put }) {
      let user = localStorage.getItem('user');
      if (user) {
        user = JSON.parse(user);
      }
      if (user) {
        const power = Role[user.roleId] || [];
        setAuthority(power);
        reloadAuthorized();
        yield put({
          type: `${Reducers.saveCurrentUser}`,
          payload: user,
        });
      } else {
        yield put({
          type: 'login/logout',
        });
      }
    },
  },
  reducers: {
    [Reducers.saveArea](state, { payload = [] }) {
      return {
        ...state,
        area: payload,
      };
    },
    [Reducers.saveWorkerType](state, { payload = [] }) {
      return {
        ...state,
        workerType: payload,
      };
    },
    [Reducers.saveCurrentUser](state, { payload }) {
      localStorage.setItem('user', JSON.stringify(payload));
      return {
        ...state,
        currentUser: payload,
      };
    },

    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
